import requests
from fastapi import APIRouter, Request
from fastapi.responses import RedirectResponse, HTMLResponse
from auth.utils import get_current_user_info
from fastapi.templating import Jinja2Templates
from logging_config import setup_logging
logger=setup_logging()
router = APIRouter()
templates = Jinja2Templates(directory="templates")

# 进入 AI 医生页面
@router.get("/ai", response_class=HTMLResponse)
def ai_page(request: Request):
    username, role = get_current_user_info(request)
    logger.info(f"{username}访问AI助手")
    if not username:
        return RedirectResponse("/login")

    # 只有普通用户能访问
    if role != "user":
        return HTMLResponse("<script>alert('只有普通用户才能使用 AI 医生');history.back()</script>")

    return templates.TemplateResponse("ai_doctor.html", {"request": request})

# AI 医生回答（本地 LLM）
@router.post("/ai/ask")
async def ai_ask(body: dict):
    logger.info("询问AI助手")
    question = body.get("question", "")
    try:
        # 打印请求的 question 和 API URL

        response = requests.post(
            "http://localhost:11434/api/generate",  # 本地 Ollama API 地址
            json={
                "model": "qwen2.5",  # 使用的模型名称
                "prompt": question,
                "stream": False
            }
        )

        response_data = response.json()
        answer = response_data.get("response", "AI 暂时无法回答")
    except Exception as e:
        answer = "AI 服务暂时不可用，请稍后再试。"

    return {"answer": answer}
